﻿using log4net;
using Microsoft.VisualBasic.ApplicationServices;
using StoreProject.BLL;
using StoreProject.DAL;
using StoreProject.DBUtil;
using StoreProject.Entity;
using StoreProject.Entity.OtherEntity;
using StoreProject.Forms.UserControls;
using StoreProject.OtherEntity.DB;
using StoreProject.OtherUtil;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StoreProject.Forms
{
    public partial class MainForm : Form
    {
        ILog _log = LogManager.GetLogger("Form1");
        CreeateOrderForm createForm;
        PrintBoxNumForm printBoxNumForm;
        PrintOrderForm printOrderForm;
        SettingForm settingForm;
        StackManageForm stackManageForm;
        OrderQueryAndEditForm orderQueryAndEditForm;
        ChangefulBLL changefulBLL = new ChangefulBLL();
        BoxNumBLL boxNumBLL = new BoxNumBLL();
        private bool _needChageDb = false;
        IniConfig iniConfig = null;
        IniConfig useAbleConfig = null;
        bool isAdmin = true;        //判断是否显示编辑查询制令单的右键菜单是否显示

        public MainForm()
        {
            iniConfig = new IniConfig("DbSetting.ini");
            var flag = iniConfig.KeyExists("BackPath", "MySQLSetting");
            if (!flag)
                iniConfig.Write("BackPath","D:/", "MySQLSetting");
            useAbleConfig = new IniConfig("UseAbleSetting.ini");
            _needChageDb = IsKeyPushedDown(Keys.ShiftKey);
            if (_needChageDb)
            {
                _needChageDb = false;
                //DBConnSetting set = RegistryUtil.GetDbConfig();
                DBConnSetting set = GetDbConfig();
                OpenSettingForm(set);
            }
            InitializeComponent();
        }
        private void OpenSettingForm(DBConnSetting set)
        {
            DBSettingForm dbForm = new DBSettingForm(set);
            dbForm.StartPosition = FormStartPosition.CenterScreen;
            dbForm.SaveConfigHandler += DbForm_SaveConfigHandler;
            dbForm.TopMost = true;
            dbForm.ShowDialog();
            dbForm.BringToFront();
        }
        private void DbForm_SaveConfigHandler(bool success)
        {
            if (!success)
            {
                MessageBox.Show("保存数据库设置失败！程序将退出。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
        }
        public static bool IsKeyPushedDown(System.Windows.Forms.Keys vKey)
        {
            return 0 != (Win32Helper.GetAsyncKeyState((int)vKey) & 0x8000);
        }
        private void btnCreateOrderNum_Click(object sender, EventArgs e)
        {
            createForm = new CreeateOrderForm();
            createForm.FormClosed += CreateForm_FormClosed;
            createForm.ShowDialog();
        }
        private void CreateForm_FormClosed(object? sender, FormClosedEventArgs e)
        {
            createForm = null;
        }
        private void btnPrintOrderNum_Click(object sender, EventArgs e)
        {
            printOrderForm = new PrintOrderForm();
            printOrderForm.FormClosed += PrintOrderForm_FormClosed;
            printOrderForm.ShowDialog();
        }

        private void PrintOrderForm_FormClosed(object? sender, FormClosedEventArgs e)
        {
            printOrderForm = null;
        }

        private void btnPrintBoxNum_Click(object sender, EventArgs e)
        {
            printBoxNumForm = new PrintBoxNumForm();
            printBoxNumForm.FormClosed += PrintBoxNumForm_FormClosed;
            printBoxNumForm.ShowDialog();
        }

        private void PrintBoxNumForm_FormClosed(object? sender, FormClosedEventArgs e)
        {
            printBoxNumForm = null;
        }

        private void btnSeting_Click(object sender, EventArgs e)
        {
            settingForm = new SettingForm();
            settingForm.FormClosed += SettingForm_FormClosed;
            settingForm.ShowDialog();
        }

        private void SettingForm_FormClosed(object? sender, FormClosedEventArgs e)
        {
            settingForm = null;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            //DBConnSetting set = RegistryUtil.GetDbConfig();
            DBConnSetting set = GetDbConfig();
            if (!ValidDbSettingRule.ValidDBSetting(set))
            {
                OpenSettingForm(set);
            }
            var flag = useAbleConfig.KeyExists("IsAdmin", "User");
            if (flag)
            {
                var temp = useAbleConfig.Read("IsAdmin", "User");
                if (!string.IsNullOrEmpty(temp))
                {
                    for (int i = 0; i < temp.Length; i++)
                    {
                        if (i == 0 && temp[i] == '1')
                        {
                            this.btnCreateOrderNum.Enabled = true;
                        }
                        else if (i == 1 && temp[i] == '1')
                        {
                            this.btnPrintOrderNum.Enabled = true;
                        }
                        else if (i == 2 && temp[i] == '1')
                        {
                            this.btnStackManage.Enabled = true;
                        }
                        else if (i == 3 && temp[i] == '1')
                        {
                            this.btnEditOrder.Enabled = true;
                        }
                        else if (i == 3 && temp[i] == '2')
                        {
                            this.btnEditOrder.Enabled = true;
                            isAdmin = false;
                        }
                        else if (i == 4 && temp[i] == '1')
                        {
                            this.btnExport.Enabled = true;
                        }
                        else if (i == 5 && temp[i] == '1')
                        {
                            this.btnSeting.Enabled = true;
                        }
                    }
                }
            }
            else
            {
                useAbleConfig.Write("IsAdmin", "000000", "User");
                this.btnCreateOrderNum.Enabled = false;
                this.btnPrintOrderNum.Enabled = false;
                this.btnEditOrder.Enabled = false;
                this.btnExport.Enabled = false;
                this.btnSeting.Enabled = false;
                this.btnPrintBoxNum.Enabled = false;
                this.btnStackManage.Enabled = false;
            }
        }

        private DBConnSetting GetDbConfig()
        {
            DBConnSetting set = new DBConnSetting();
            try
            {
                var flag = iniConfig.KeyExists("Server", "MySQLSetting");
                if (!flag)
                    return null;
                flag = iniConfig.KeyExists("DbName", "MySQLSetting");
                if (!flag)
                    return null;
                flag = iniConfig.KeyExists("User", "MySQLSetting");
                if (!flag)
                    return null;
                flag = iniConfig.KeyExists("Psw", "MySQLSetting");
                if (!flag)
                    return null;
                set.Server = iniConfig.Read("Server", "MySQLSetting");
                set.DbName = iniConfig.Read("DbName", "MySQLSetting");
                string user = iniConfig.Read("User", "MySQLSetting");
                if (user != string.Empty)
                    set.User = Base64Util.Base64Decode(Encoding.UTF8,user);//DataProtector.DecryptLocalMachine(user, DataProtector.SALT);
                string psw = iniConfig.Read("Psw", "MySQLSetting");
                if (psw != string.Empty)
                    set.Psw = Base64Util.Base64Decode(Encoding.UTF8, psw);//DataProtector.DecryptLocalMachine(psw, DataProtector.SALT);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return set;
        }

        private void btnEditOrder_Click(object sender, EventArgs e)
        {
            orderQueryAndEditForm = new OrderQueryAndEditForm(isAdmin);
            orderQueryAndEditForm.FormClosed += OrderQueryAndEditForm_FormClosed;
            orderQueryAndEditForm.ShowDialog();
        }

        private void OrderQueryAndEditForm_FormClosed(object? sender, FormClosedEventArgs e)
        {
            orderQueryAndEditForm = null;
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            var list = boxNumBLL.GetList().OrderByDescending(x=>x.CreateTime).ToList();
            if (list == null || list.Count < 1)
            {
                MessageBox.Show("没有数据可导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "CSV files (*.csv)|*.csv";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.FileName = null;
            saveFileDialog.Title = "保存";
            DateTime now = DateTime.Now;
            saveFileDialog.FileName = "箱号数据汇总"+ now.Year.ToString().PadLeft(2) + now.Month.ToString().PadLeft(2, '0') + now.Day.ToString().PadLeft(2, '0') + "-" + now.Hour.ToString().PadLeft(2, '0') + now.Minute.ToString().PadLeft(2, '0') + now.Second.ToString().PadLeft(2, '0');
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                Stream stream = saveFileDialog.OpenFile();
                StreamWriter sw = new StreamWriter(stream, System.Text.Encoding.GetEncoding(-0));
                string strLine = "";
                try
                {
                    StringBuilder data = new StringBuilder();
                    //写出列名称-第一行
                    data.Append("制令单号,成品名称,线型,批号,操作人,卷号,毛重,整箱数量,库位,总数量,箱号,创建时间");
                    //换行
                    sw.WriteLine(data);
                    foreach (var item in list)
                    {
                        data = new StringBuilder();
                        data.Append(item.OrderId);
                        data.Append(",");
                        data.Append(item.FinishedProductName);
                        data.Append(",");
                        data.Append(item.LineType);
                        data.Append(",");
                        data.Append(item.Batch);
                        data.Append(",");
                        data.Append(item.Operator);
                        data.Append(",");
                        data.Append(item.JuanNum);
                        data.Append(",");
                        data.Append(item.MaoZhong);
                        data.Append(",");
                        data.Append(item.OneBoxCount);
                        data.Append(",");
                        data.Append(item.Store);
                        data.Append(",");
                        data.Append(item.AllCount);
                        data.Append(",");
                        data.Append(item.BoxNum);
                        data.Append(",");
                        data.Append(item.CreateTime);
                        data.Append(",");
                        //换行
                        sw.WriteLine(data);
                    }
                    sw.Close();
                    stream.Close();
                    MessageBox.Show("数据被导出到：" + saveFileDialog.FileName.ToString(), "导出完毕", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "导出错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
        }

        private void btnStackManage_Click(object sender, EventArgs e)
        {
            stackManageForm = new StackManageForm();
            stackManageForm.FormClosed += StackManageForm_FormClosed; ;
            stackManageForm.ShowDialog();
        }

        private void StackManageForm_FormClosed(object? sender, FormClosedEventArgs e)
        {
            stackManageForm = null;
        }
    }
}
